package com.smarthome.ipc.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.smarthome.common.httpwapper.HttpRequester;
import com.smarthome.common.httpwapper.HttpResponse;
import com.smarthome.ipc.util.IpcConfig;
import com.smarthome.ipc.util.MacHelper;

@Service
public class GetIpService {
	
	private Log LOGGER = LogFactory.getLog(getClass());
	
	public void synchrNetip() throws Exception{
		String centerIp = IpcConfig.getValue(IpcConfig.CENTER_SEVER_IP);
		String res = sendUrl(centerIp, IpcConfig.SEVER_GETIP, null);
		if(res == null){
			throw new Exception("获取IP失败");
		}
		LOGGER.info("中央服务器返回："+res);
		JSONObject resObj = (JSONObject) JSONObject.parse(res);
		String netIp = resObj.getString("data");
		if(StringUtils.isBlank(IpcConfig.LOCAL_NET_IP) || !IpcConfig.LOCAL_NET_IP.equals(netIp)){
			String mac = MacHelper.getMac("192.168.0.4");
			Map<String,String> params = new HashMap<String,String>();
			params.put("macAddr", mac);
			String back = sendUrl(centerIp, IpcConfig.SEVER_RECORD_IP, params);
			JSONObject backObj = (JSONObject) JSONObject.parse(back);
			String code = backObj.getString("code");
			if("ok".equals(code)){
				LOGGER.info("更新IP成功");
				IpcConfig.LOCAL_NET_IP = netIp;
			}else{
				throw new Exception("更新IP失败");
			}
		}
	}
	
	public String sendUrl(String ipcUrl, String method, Map<String, String> params) {
		ipcUrl = "http://" + ipcUrl;
		ipcUrl += method;
        if (null == params)
            params = new HashMap<String, String>();
        try {
        	String url = formatParam(ipcUrl, params);
        	LOGGER.info("请求地址：" + url);
            HttpResponse response = HttpRequester.sendGet(url, params);
            if (response.getStatusCode() == 200)
                return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private String formatParam(String ipcUrl,Map<String, String> params){
    	if(params == null){
    		return ipcUrl;
    	}
    	StringBuilder url = new StringBuilder(ipcUrl+"?");
    	for(String key : params.keySet()){
    		url.append(key);
    		url.append("=");
    		url.append(params.get(key));
    		url.append("&");
    	}
    	return url.toString();
    }
}
